const jwt = require('jsonwebtoken')
const { createUser,getUserInfo,upDataById } = require('../service/user.service')
const {userRegisterError,upDateErr } = require('../constant/err.type')
const {JWT_SECRET} = require('../config/config.default')
class UserController {
    async register(ctx, next) {
        const { user_account,password } = ctx.request.body
        try {
            const res = await createUser(user_account,password)
            ctx.body = {
                code: 0,
                msg: '用户注册成功',
                result: {
                    id: res.id,
                    user_account: res.user_account,
                }
            }
        } catch (err) {
            console.error('用户注册错误',err)
            ctx.app.emit('error',userRegisterError,ctx)
            return
        }
    }

    async login(ctx, next) {
        const {user_account} = ctx.request.body
        // token验证
        try {
            const {password,...res} = await getUserInfo({user_account})
            ctx.body = {
                code: 0,
                msg: '用户登录成功',
                result: {
                    token: jwt.sign(res,JWT_SECRET,{expiresIn: '1d'})
                }
            }
        }catch (err) {
            console.error('用户登录失败',err)
        }

    }
    async changePassword (ctx,next) {
        const id = ctx.state.user.id
        const  password = ctx.request.body.password
        if(await upDataById({id,password})) {
            ctx.body = {
                code:0,
                msg: '修改密码成功',
                result: ''
            }
        }else {
            console.error('修改密码错误',err)
            ctx.app.emit('error',upDateErr,ctx)
        }
    }

    // 返回用户信息
    async info (ctx,next) {
        const id = ctx.state.user.id
        let info = {
            roles: ctx.state.user.roles.split(','),
            introduction: ctx.state.user.introduction,
            avatar: ctx.state.user.avatar,
            name: ctx.state.user.name,
            time: ctx.state.user.createdAt,
            phone: ctx.state.user.phone,
        }
        ctx.body = {
            code: 0,
            data: info
        }
    }
}

module.exports = new UserController()